﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SqlExecuter.Client.Model
{
    public class FsDirectory : FileSystemItem, IDisposable
    {
        public List<FsFile> Files { get; set; }
        public List<FsDirectory> SubDirectories { get; set; }
        public List<FileSystemItem> DirectoriesAndFiles { get; set; }

        private void Initialize()
        {
            Files = new List<FsFile>();
            SubDirectories = new List<FsDirectory>();
            DirectoriesAndFiles = new List<FileSystemItem>();
        }
        public FsDirectory()
            : base()
        {
            Initialize();
        }

        public FsDirectory(DirectoryInfo di)
            : base(di.Name, di.FullName)
        {
            Initialize();
            try
            {
                Files.AddRange(FsFile.GetFiles(di.GetFiles("*.sql")));
                SubDirectories.AddRange(FsDirectory.GetDirectories(di.GetDirectories()));
                DirectoriesAndFiles.AddRange(Files);
                DirectoriesAndFiles.AddRange(SubDirectories);
            }
            catch (Exception)
            {
                // In case there is an access violation for some directories, just ignore them and continue.
            }

        }

        public static List<FsDirectory> GetDirectories(IEnumerable<DirectoryInfo> directories)
        {
            List<FsDirectory> convertedItems = new List<FsDirectory>();
            foreach (DirectoryInfo directory in directories)
                convertedItems.Add(new FsDirectory(directory));
            return convertedItems;
        }

        public void Dispose()
        {
            SubDirectories.ForEach(d => d.Dispose());
            DirectoriesAndFiles.Clear();
        }
    }
}
